package es.onlysolutions.gs.comm.utils;

import com.google.gdata.data.media.mediarss.MediaThumbnail;
import com.google.gdata.data.youtube.VideoEntry;

import java.util.List;
import java.util.StringTokenizer;
import java.util.ArrayList;

import org.springframework.util.Assert;

/**
 * Static class to extract easily properties of video objects.
 */
public final class VideoUtils
{

    /**
     * Get the url of the Video extracting the media.
     * @param videoEntry The VideoEntry.
     * @return The URL to the image. Loop to find the bigger image size.
     */
    public static String getImageUrl(VideoEntry videoEntry)
    {
        Assert.notNull( videoEntry, "The VideoEntry param cannot be null" );
        String url = "";
        
        List<MediaThumbnail> thumbnails = videoEntry.getMediaGroup().getThumbnails();
        int heigth = 0;
        for (MediaThumbnail mediaThumbnail : thumbnails)
        {
            if( heigth < mediaThumbnail.getHeight() )
            {
                url = mediaThumbnail.getUrl();
                heigth = mediaThumbnail.getHeight();
            }
        }

        return url;
    }

    /**
     * Get the YouTube ID from the VideoEntry.
     * @param videoEntry The VideoEntry to get the id.
     * @return The YouTube ID.
     */
    public static String extractYouTubeId(VideoEntry videoEntry)
    {
        Assert.notNull( videoEntry, "The VideoEntry param cannot be null" );

        String gdataId = videoEntry.getId();
        return extractYouTubeIdFromGdataId( gdataId );
    }

    public static String extractYouTubeIdFromGdataId( String gdataId )
    {
        Assert.hasLength( gdataId, "The gdata ID cannot be empty" );

        int lastIndexOfSlash = gdataId.lastIndexOf('/');
        Assert.isTrue( lastIndexOfSlash > 0, "Is not a valid GdataId: " + gdataId );

        return gdataId.substring( lastIndexOfSlash+1 );
    }


    /**
     * From a string with 0 o more keywords separate by comas, this methos returns a list of Strings with every keyword
     * without blanks.
     * @param keyWords The string from where extract the keywords.
     * @return The keywords list.
     */
    public static List<String> getKeywordsArray(String keyWords)
    {
        List<String> result = new ArrayList<String>(7);

        if( keyWords != null && keyWords.trim().length() > 0 )
        {
            StringTokenizer st = new StringTokenizer(keyWords, ",");
            while( st.hasMoreTokens() )
            {
                result.add( st.nextToken().trim() );
            }
        }

        return result;
    }
}
